package com.njwb.interceptor;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.njwb.constant.Code;
import com.njwb.json.Result;
import com.njwb.util.JWTUtil;
import com.njwb.util.JsonUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.HashMap;
import java.util.Map;

/**
 * 鉴权拦截器，会在请求到达之前被执行
 */
@Component
public class AuthorizationInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Map<String, Object> map = new HashMap<>();
        // 获取请求头中的token
        String token = request.getHeader(HttpHeaders.AUTHORIZATION);
        Result result = new Result();
        //获取的token格式为
        //Bearer x.y.z
        token = token.split("\\s+")[1];//没有token的格式  Bearer  null
        if("null".equals(token)){
            //未登录
            result.setCode(Code.AUTH_ERROR);
            result.setCodeMsg(Code.AUTH_ERROR_MSG);
        }else{
            try{
                DecodedJWT decodedJWT = JWTUtil.verfiyJWT(token);
                return  true;//进入后续请求中
            }catch (Exception e){
                //鉴权不通过
                result.setCode(Code.AUTH_ERROR);
                result.setCodeMsg(Code.AUTH_ERROR_MSG);
            }
        }
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(JsonUtil.toJson(result));
        return false;
    }
}
